﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MyWorkBlogDAL
{
   public partial class Blog
    {
       
       public static List<Blog> GetBlogs()
       {
           var query = BlogDB.Blogs
               .Select(n => n).ToList();
           return query;

       }

       public static List<Blog> GetBlogsWithPost()
       {
           //var query = BlogDB.BlogPosts.Include("Blogs")
           //    .Select(n => n.Blog).ToList();
           //return query;

           var query = (from b in BlogDB.Blogs
               from p in BlogDB.BlogPosts

               where b.BlogId == p.BlogId
               select b).Distinct();
           return query.ToList();

       }

       public static Blog IsAllowed(string username, string password)
       {
           var query = BlogDB.Blogs
               .SingleOrDefault(n => n.Username == username && n.Password == password);
         
               
           return query;
       }
       public static Blog GetBlog(string username)
       {
           var query = BlogDB.Blogs
               .FirstOrDefault(n => n.Username == username);
           
           return query;

       }
       public static Blog GetBlogWithBlogId(int blogId)
       {
           var query = BlogDB.Blogs
               .Single(n => n.BlogId == blogId);

           return query;

       }
      
       public static bool HasPost(int blogId)
       {
           
           var query = BlogDB.Blogs.Include("BlogPosts");
           return query.Any(n => n.BlogId == blogId);
       }
       public static int InsertBlog(Blog blog)
       {
           var usernameExist = BlogDB.Blogs
               .Any(n => n.Username == blog.Username);
           if (usernameExist)
           {
               return -1;
           }
         
           BlogDB.Blogs.Add(blog);
        return BlogDB.Save();
       }

       public static bool IsValidPassword(string username, string password)
       {
           var query = BlogDB.Blogs
               .Any(n => n.Username == username && n.Password == password);
           return query;
       }
       public static int UpdateBlog(Blog blog)
       {
           var query = BlogDB.Blogs
               .FirstOrDefault(n => n.BlogId == blog.BlogId && n.Username == blog.Username);
           if (query != null)
           {
               query.Name = blog.Name;
               query.Country = blog.Country;
               query.Description = blog.Description;
               query.Password = blog.Password;
           }
           

           BlogDB.Blogs.AddOrUpdate(query);
           return BlogDB.Save();
       }
     


    }
}
